// controllers/weather.js
const axios = require('axios');
const Redis = require('ioredis');
const { promisify } = require('util');
const dotenv = require('dotenv');
const errorHandler = require('../utils/errorHandler');

dotenv.config();

const CACHE_TTL = 600; // 10分钟
const OWM_API_KEY = process.env.OWM_API_KEY;
const redis = new Redis(process.env.REDIS_URL);

// 将 Redis 方法转换为 Promise
const getAsync = promisify(redis.get).bind(redis);
const setexAsync = promisify(redis.setex).bind(redis);

module.exports = async (req, res) => {
  const { city, units = 'metric', lang = 'zh_cn' } = req.query;
  const cacheKey = `weather:${city.toLowerCase()}:${units}:${lang}`;

  try {
    // 1. 检查缓存
    const cachedData = await getAsync(cacheKey);
    if (cachedData) {
      console.log('缓存命中:', cacheKey);
      return res.json(JSON.parse(cachedData));
    }

    // 2. 调用天气API
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${units}&lang=${lang}&appid=${OWM_API_KEY}`;
    const response = await axios.get(apiUrl);

    // 3. 数据格式化
    const formattedData = {
      city: response.data.name,
      temp: response.data.main.temp,
      feels_like: response.data.main.feels_like,
      humidity: response.data.main.humidity,
      wind_speed: response.data.wind.speed,
      description: response.data.weather[0].description,
      icon: `https://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`
    };

    // 4. 写入缓存
    await setexAsync(cacheKey, CACHE_TTL, JSON.stringify(formattedData));

    res.json(formattedData);
  } catch (error) {
    errorHandler(error, res);
  }
};